<template>
  <div class="user-management">
    <h2>用户管理</h2>
    
    <!-- 筛选区域：使用Element Plus表单组件 -->
    <el-form 
      :model="filters" 
      class="filter-section" 
      inline 
      label-width="80px"
    >
      <el-form-item label="用户名" prop="username">
        <el-input 
          v-model="filters.username" 
          placeholder="请输入用户名" 
          clearable
          @clear="resetFilters"
        />
      </el-form-item>
      
      <el-form-item label="性别" prop="gender">
        <el-select 
          v-model="filters.gender" 
          placeholder="请选择性别"
          clearable
        >
          <el-option value="all">全部</el-option>
          <el-option value="1">男</el-option>
          <el-option value="2">女</el-option>
        </el-select>
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" @click="searchUsers">搜索</el-button>
      </el-form-item>
      
      <el-form-item>
        <el-button @click="resetFilters">重置</el-button>
      </el-form-item>
    </el-form>
    
    <!-- 表格区域：使用Element Plus表格 -->
    <div class="user-table-container">
      <el-table 
        v-loading="loading" 
        :data="filteredUsers" 
        border 
        stripe 
        style="width: 100%"
        :empty-text="error || (filteredUsersTotal > 0 ? '加载中...' : '暂无数据')"
      >
        <el-table-column label="用户名" prop="userName" align="center">
          <template #default="scope">
            {{ scope.row.userName || '-' }}
          </template>
        </el-table-column>
        
        <el-table-column label="性别" align="center">
          <template #default="scope">
            {{ Number(scope.row.gender) === 1 ? '男' : Number(scope.row.gender) === 2 ? '女' : '-' }}
          </template>
        </el-table-column>
        
        <el-table-column label="注册时间" prop="createTime" align="center">
          <template #default="scope">
            {{ formatTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        
        <el-table-column label="更新时间" prop="updateTime" align="center">
          <template #default="scope">
            {{ formatTime(scope.row.updateTime) }}
          </template>
        </el-table-column>
        
        <el-table-column label="状态" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" align="center" width="200">
          <template #default="scope">
            <el-button 
              type="primary" 
              size="small" 
              @click="viewUserDetails(scope.row)"
            >
              详情
            </el-button>
            <el-button 
              type="warning" 
              size="small" 
              @click="resetPassword(scope.row)"
              style="margin-left: 8px"
            >
              重置密码
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <!-- 分页区域：使用Element Plus分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="filteredUsersTotal"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 用户详情弹窗：使用Element Plus对话框 -->
    <el-dialog 
      title="用户详情" 
      v-model="showUserDetails" 
      width="700px"
      @close="closeDetailsModal"
    >
      <!-- 基础信息卡片 -->
      <el-card class="detail-card mb-4">
        <template #header>
          <div class="card-header">
            <span>基础信息</span>
          </div>
        </template>
        <div class="grid-container">
          <div class="grid-item">
            <span class="label">用户名：</span>
            <span class="value">{{ selectedUser.userName || '-' }}</span>
          </div>
          <div class="grid-item">
            <span class="label">性别：</span>
            <span class="value">{{ Number(selectedUser.gender) === 1 ? '男' : Number(selectedUser.gender) === 2 ? '女' : '-' }}</span>
          </div>
          <div class="grid-item">
            <span class="label">紧急联系人：</span>
            <span class="value">{{ selectedUser.emergencyName || '-' }}</span>
          </div>
          <div class="grid-item">
            <span class="label">紧急联系电话：</span>
            <span class="value">{{ selectedUser.emergencyPhone || '-' }}</span>
          </div>
          <div class="grid-item full-width">
            <span class="label">地址：</span>
            <span class="value">{{ selectedUser.address || '-' }}</span>
          </div>
        </div>
      </el-card>
      
      <!-- 账号信息卡片 -->
      <el-card class="detail-card">
        <template #header>
          <div class="card-header">
            <span>账号信息</span>
          </div>
        </template>
        <div class="grid-container">
          <div class="grid-item">
            <span class="label">注册时间：</span>
            <span class="value">{{ formatTime(selectedUser.createTime) }}</span>
          </div>
          <div class="grid-item">
            <span class="label">更新时间：</span>
            <span class="value">{{ formatTime(selectedUser.updateTime) }}</span>
          </div>
          <div class="grid-item">
            <span class="label">账号状态：</span>
            <span class="value">
              <el-tag :type="selectedUser.status === 1 ? 'success' : 'danger'">
                {{ selectedUser.status === 1 ? '正常' : '禁用' }}
              </el-tag>
            </span>
          </div>
        </div>
      </el-card>
    </el-dialog>
    
    <!-- 重置密码弹窗：使用Element Plus对话框 -->
    <el-dialog 
      title="重置密码" 
      v-model="showResetPassword" 
      width="400px"
      @close="closeResetPasswordModal"
    >
      <div class="reset-pwd-content">
        <p>确定要重置用户 <span class="user-name">{{ resetTargetUser.userName }}</span> 的密码吗？</p>
        <el-alert 
          title="重置后的密码将默认为：123456" 
          type="warning" 
          show-icon 
          style="margin-top: 16px"
        />
      </div>
      <template #footer>
        <el-button @click="closeResetPasswordModal">取消</el-button>
        <el-button type="primary" @click="confirmResetPassword">确认重置</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import api from '@/utils/axiosConfig'
// 引入Element Plus组件（若使用自动导入可省略）
import { 
  ElTable, ElTableColumn, ElButton, ElForm, ElFormItem, 
  ElInput, ElSelect, ElOption, ElPagination, ElDialog, 
  ElTag, ElAlert, ElLoading, ElMessage 
} from 'element-plus'

export default {
  name: 'UserManagement',
  components: {
    ElTable, ElTableColumn, ElButton, ElForm, ElFormItem,
    ElInput, ElSelect, ElOption, ElPagination, ElDialog,
    ElTag, ElAlert, ElLoading, ElMessage
  },
  setup() {
    const currentPage = ref(1)
    const pageSize = ref(10)
    const showUserDetails = ref(false)
    const showResetPassword = ref(false)
    const selectedUser = ref({})
    const resetTargetUser = ref({})
    const loading = ref(false)
    const error = ref('')
    
    // 筛选条件
    const filters = reactive({
      username: '',
      gender: 'all'
    })
    
    // 用户列表数据
    const users = ref([])
    
    // 格式化时间
    const formatTime = (timeString) => {
      if (!timeString) return '-'
      try {
        const date = new Date(timeString)
        return date.toLocaleString('zh-CN', { 
          year: 'numeric', 
          month: '2-digit', 
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        })
      } catch (e) {
        console.error('时间格式化错误:', e)
        return timeString
      }
    }
    
    // 获取用户列表
    const fetchUsers = async () => {
      loading.value = true
      error.value = ''
      try {
        const response = await api.get('/user/list')
        let allUsers = Array.isArray(response.data) ? response.data : []
        // 筛选普通用户（userType为1）
        users.value = allUsers.filter(user => user.userType === 1)
        // 重置分页到第一页
        currentPage.value = 1
      } catch (err) {
        console.error('获取用户列表失败:', err)
        error.value = '获取用户列表失败，请稍后重试'
      } finally {
        loading.value = false
      }
    }
    
    // 筛选后的用户列表（未分页）
    const filteredUsersRaw = computed(() => {
      let result = [...users.value]
      
      // 用户名筛选
      if (filters.username) {
        const searchTerm = filters.username.toLowerCase()
        result = result.filter(user => 
          user.userName && user.userName.toLowerCase().includes(searchTerm)
        )
      }
      
      // 性别筛选
      if (filters.gender !== 'all' && filters.gender !== null && filters.gender !== '') {
        const genderFilter = Number(filters.gender);
        result = result.filter(user => Number(user.gender) === genderFilter);
      }
      
      return result
    })
    
    // 筛选后的用户列表总数
    const filteredUsersTotal = computed(() => {
      return filteredUsersRaw.value.length
    })
    
    // 筛选后的用户列表（带分页）
    const filteredUsers = computed(() => {
      // 防止currentPage超出范围
      const totalPages = Math.ceil(filteredUsersRaw.value.length / pageSize.value)
      if (currentPage.value > totalPages && totalPages > 0) {
        currentPage.value = totalPages
      }
      
      const startIndex = (currentPage.value - 1) * pageSize.value
      return filteredUsersRaw.value.slice(startIndex, startIndex + pageSize.value)
    })
    
    // 分页大小改变
    const handleSizeChange = (val) => {
      pageSize.value = val
      currentPage.value = 1 // 重置到第一页
    }
    
    // 当前页改变
    const handleCurrentChange = (val) => {
      // 确保页码在有效范围内
      const totalPages = Math.ceil(filteredUsersRaw.value.length / pageSize.value)
      if (val >= 1 && val <= totalPages) {
        currentPage.value = val
      } else if (totalPages > 0) {
        currentPage.value = totalPages
      } else {
        currentPage.value = 1
      }
    }
    
    // 搜索用户
    const searchUsers = () => {
      currentPage.value = 1
      // 仅重置页码，使用computed属性filteredUsers进行筛选，不需要重新获取数据
    }
    
    // 重置筛选条件
    const resetFilters = () => {
      filters.username = ''
      filters.gender = 'all'
      currentPage.value = 1
      // 重置时也应该清空错误信息
      error.value = ''
      fetchUsers()
    }
    
    // 查看用户详情
    const viewUserDetails = (user) => {
      selectedUser.value = { ...user }
      showUserDetails.value = true
    }
    
    // 关闭详情弹窗
    const closeDetailsModal = () => {
      showUserDetails.value = false
      selectedUser.value = {}
    }
    
    // 打开重置密码弹窗
    const resetPassword = (user) => {
      resetTargetUser.value = { ...user }
      showResetPassword.value = true
    }
    
    // 关闭重置密码弹窗
    const closeResetPasswordModal = () => {
      showResetPassword.value = false
      resetTargetUser.value = {}
    }
    
    // 确认重置密码
    // 确认重置密码
    const confirmResetPassword = async () => {
      console.log('重置目标用户数据:', resetTargetUser.value)
      
      // 直接访问用户ID属性
      let userId = resetTargetUser.value?.userId
      
      console.log('直接获取的userId:', userId)
      
      // 确保有有效的用户ID
      if (userId === undefined || userId === null || userId === '') {
        console.error('缺少有效的用户ID')
        ElMessage.warning('用户信息不完整，无法重置密码')
        return
      }
      
      try {
        // 使用修改密码的专用接口
        const response = await api.post('/user/changePassword', {
          userId: userId,
          oldPassword: resetTargetUser.value.password || '', // 原密码可以为空，因为是管理员重置
          newPassword: '123456' // 默认重置密码
        })
        
        showResetPassword.value = false
        ElMessage.success(`用户 ${resetTargetUser.value.userName} 的密码已重置为默认密码`)
        resetTargetUser.value = {}
      } catch (err) {
        console.error('重置密码失败:', err)
        console.error('错误详情:', err.response?.data || err.message)
        ElMessage.error('重置密码失败，请稍后重试')
      }
    }
    
    // 页面加载时获取数据
    onMounted(() => {
      fetchUsers()
    })
    
    return {
      filters,
      users,
      filteredUsers,
      currentPage,
      pageSize,
      showUserDetails,
      showResetPassword,
      selectedUser,
      resetTargetUser,
      loading,
      error,
      formatTime,
      fetchUsers,
      searchUsers,
      resetFilters,
      viewUserDetails,
      closeDetailsModal,
      resetPassword,
      closeResetPasswordModal,
      confirmResetPassword,
      handleSizeChange,
      handleCurrentChange
    }
  }
}
</script>

<style scoped>
/* 主容器样式 */
.user-management {
  background-color: #fff;
  border-radius: 4px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin: 0 24px;
  box-sizing: border-box;
}

.user-management h2 {
  color: #333;
  margin-bottom: 24px;
  font-size: 20px;
  font-weight: 600;
  border-bottom: 2px solid var(--el-color-primary);
  padding-bottom: 12px;
}

/* 筛选区域样式 */
.filter-section {
  margin-bottom: 24px;
  padding: 16px 20px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

/* 表格区域样式 */
.user-table-container {
  margin-bottom: 32px;
  background-color: white;
  border-radius: 8px;
  overflow: hidden;
}

/* 分页区域样式 */
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
  padding: 15px;
  background-color: #ffffff;
}

/* 表格容器样式 */
.user-table-container {
  margin-bottom: 20px;
}

/* 确保分页组件在数据为空时隐藏 */
:deep(.el-pagination.is-background) {
  &:only-child {
    margin: 0;
  }
}

/* 处理分页按钮样式 */
:deep(.el-pagination .btn-prev),
:deep(.el-pagination .btn-next),
:deep(.el-pagination .el-pager li) {
  transition: all 0.2s ease;
}

:deep(.el-pagination .el-pager li:hover:not(.disabled):not(.active)) {
  color: var(--el-color-primary);
  transform: translateY(-1px);
}

/* 响应式调整 - 小屏幕上分页居中 */
@media (max-width: 768px) {
  .pagination {
    justify-content: center;
    padding: 12px 16px;
  }
}


/* 详情卡片样式 */
.detail-card {
  margin-bottom: 16px;
  border-radius: 4px;
  border: 1px solid #ebeef5;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.detail-card .card-header {
  font-weight: 600;
  font-size: 16px;
  color: #303133;
}

/* 网格布局样式 */
.grid-container {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
  padding: 8px 0;
}

.grid-item {
  display: flex;
  align-items: center;
  padding: 8px 0;
}

.grid-item.full-width {
  grid-column: 1 / -1;
}

.grid-item .label {
  font-weight: 500;
  color: #606266;
  min-width: 80px;
  margin-right: 12px;
}

.grid-item .value {
  color: #303133;
  word-break: break-all;
  flex: 1;
}

/* 响应式调整 */
@media (max-width: 600px) {
  .grid-container {
    grid-template-columns: 1fr;
  }
  
  .grid-item.full-width {
    grid-column: 1;
  }
}

/* 重置密码弹窗内容样式 */
.reset-pwd-content p {
  line-height: 1.6;
  color: #666;
}

.user-name {
  color: var(--el-color-primary);
  font-weight: 500;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .user-management {
    margin: 0 12px;
    padding: 16px;
  }
  
  .filter-section {
    padding: 12px;
  }
}
</style>